<template>
    <t-modal :title="title" :width="840" :visible="visible" :switchFullscreen="true" :fullscreen="true"
             :confirmLoading="loading" @ok="() => {$emit('ok');activeKey = 0;}" @cancel="handleClose">
        <a-spin :spinning="loading">
            <a-form :form="form">
                <a-row>
                    <a-form-item class="hiddenItem">
                        <!-- uuid隐藏 -->
                        <a-input v-decorator="['uuid']" disabled type="hidden"/>
                    </a-form-item>
                    <a-col :span="12">
                        <a-form-item :label='$ct("templateNameTwo","模板名字")' :labelCol="labelCol"
                                     :wrapperCol="wrapperCol" placeholder="请输入模板名称">
                            <a-input v-decorator="['name',{ rules: [{ required: true, message: '请输入模板名字' }]}]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label='$ct("templateClassification","模板分类")' :labelCol="labelCol"
                                     :wrapperCol="wrapperCol">
                            <TDictSelectTag
															placeholder="请选择模板分类"
															dataType="static"
															textFeild="label"
															valueFeild="value"
															:dataList="templateTypeList"
															v-decorator="['type', { rules: [{ required: true, message: '请选择模板类型!'}]}]">
                            </TDictSelectTag>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
            <!--代码展示栏-->
            <a-card style="width:100%">
                <!--一级tab标签页-->
                <a-tabs default-active-key="1" @change="callback" type="card">
                    <a-tab-pane key="1" :tab='$ct("mainTable","主表")'>
                        <div :style="{ marginBottom: '16px' }">
                            <a-button class="cu-btn-primary" @click="handleAddTab" icon="plus">
                                {{$ct("add","新增")}}
                            </a-button>
                            <a-button @click="handleEditTab" type="primary" ghost :disabled="panes.length==0">
                                <a-icon type="edit"/>
                                {{$ct("edit","编辑")}}
                            </a-button>
                        </div>
                        <template v-if="panes.length==0">
                            <a-empty/>
                        </template>
                        <!--二级tab标签页-->
                        <a-tabs v-model="activeKey" hide-add type="editable-card" @edit="onEdit" v-if="panes.length!=0 && visible ">
                            <a-tab-pane v-for="(item,index) in panes" :key="index" :tab="item.tabName"
                                        :closable="item.closable" :forceRender="true">
                                <!--代码编辑器-->
                                <Monaco :ref="'monaco' + item.tabName" :data="item.tabData" height='450px' :opts="opts"></Monaco>
                            </a-tab-pane>
                        </a-tabs>
                    </a-tab-pane>
                </a-tabs>
            </a-card>
        </a-spin>
        <t-modal :title="isAdd ? $ct('add','新增') : $ct('edit','编辑')" :width="840" :visible="showTebModal" :switchFullscreen="true"
                 :confirmLoading="loading" @ok="handleOk" @cancel="cancel">
            <a-form-model :model="tabModelData" :label-col="labelCol" :wrapper-col="wrapperCol" ref="tebModal"
                          :rules="rules">
                <a-form-model-item :label="$ct('fileName','文件名')" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fileName">
                    <a-input v-model="tabModelData.fileName"/>
                </a-form-model-item>
            </a-form-model>
        </t-modal>
    </t-modal>
</template>

<script>
    import pick from "lodash.pick";
    import {Monaco} from "@/components";    // 引入monaco插件
    const fields = [
        "uuid",
        "type",
        "name",
        // "templateJson"
    ];
    import TDictSelectTag from "@/components/TopVUI/dict/TDictSelectTag";

    export default {
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            loading: {
                type: Boolean,
                default: () => false,
            },
            model: {
                type: Object,
                default: () => null,
            },
        },
        components: {
            TDictSelectTag,
            Monaco
        },
        data() {
            return {
                title: "",
                labelCol: {
                    xs: {
                        span: 24,
                    },
                    sm: {
                        span: 5,
                    },
                },
                wrapperCol: {
                    xs: {
                        span: 24,
                    },
                    sm: {
                        span: 16,
                    },
                },
                formData: [],
                templateTypeList: [{value: '单表', id: 1, label: '单表'}, {value: 'doubleForm', id: 1, label: '主附表'}],  //模板类型下拉框
                form: null,
                newTabIndex: 0,     //新增窗口索引值
                showTebModal: false,    //控制展示二级弹窗显示
                tabModelData: {fileName: ''},   //二级弹窗数据
                rules: {
                    fileName: [{required: true, message: '请输入文件名！', trigger: 'blur'},
                        {validator: this.handleFileName, message: '文件名重复！', trigger: 'blur'},
                    ],
                },  //二级弹窗 表单验证规则
                isAdd: true,    //是否为新增
                opts: {theme:'hc-black'},   //monaco配置
                panes: [], //tab页的数据
                activeKey: 0,    //当前二级tab页的key值
            }

        },
        methods: {
            add(m, data) {
                // console.log(m, data);
            },
            edit(m, data) {
                // console.log(m, data);
            },
            callback(key) {
                // console.log(key);
            },
            //
            handleClose(){
                let that = this
                that.$confirm({
                    title: that.$ct("warning","警告"),
                    content: that.$ct("sysGenTemplateCloseTips","关闭后所有未保存的数据将会清空，请谨慎操作！"),
                    okText: that.$ct("confirm","确定"),
                    okType: 'danger',
                    cancelText: that.$ct("cancel","取消"),
                    onOk() {
                        that.$emit('cancel');
                        that.activeKey = 0;
                    }
                })
            },
            //取消和关闭tab对话框的回调
            cancel() {
                // console.log("取消了")
                this.showTebModal = false;
                this.tabModelData.fileName = '';
                this.$refs.tebModal.resetFields();
                this.tabModelData.fileName = '';
            },
            //监听二级tab页的操作并调用对应的函数（增删改）
            onEdit(targetKey, action) {
                this[action](targetKey);
            },
            //提交tab对话框时判断
            handleOk() {
                this.$refs.tebModal.validate(valid => {
                    if (valid) {
                        this.isAdd ? this.addTab() : this.editTab()
                        this.showTebModal = false;
                        this.$refs.tebModal.resetFields();
                        this.tabModelData.fileName = '';

                    } else {
                        return false;
                    }
                })
            },
            //点击编辑时的处理
            handleEditTab() {
                this.showTebModal = true;
                this.isAdd = false;
                //给表单赋值errors.js?fdcc:8 Uncaught Error: Unexpected usage
                this.tabModelData.fileName = this.panes[this.activeKey].tabName;
            },
            //点击新增时的处理
            handleAddTab() {
                this.showTebModal = true;
                this.isAdd = true;
            },
            //编辑当前二级tab页
            editTab() {
                //改变当前tab页的tabName值
                this.panes[this.activeKey].tabName = this.tabModelData.fileName;
            },
            //新增二级tab页
            addTab() {
                const panes = this.panes;
                panes.push({
                    tabName: this.tabModelData.fileName,
                    tabData: ''
                });
                this.panes = panes;
                //将当前tab页设新增的页面
                this.activeKey = this.panes.length - 1;
            },
            //移除tab
            remove(targetKey) {
                let activeKey = this.activeKey;
                let lastIndex;
                this.panes.forEach((pane, index) => {
                    if (index === targetKey) {
                        //要删除的目标索引值的前一位
                        lastIndex = index - 1;
                    }
                });
                const panes = this.panes.filter((pane, index) => index !== targetKey);
                if (panes.length && activeKey === targetKey) {
                    if (lastIndex >= 0) {
                        activeKey--;
                    } else {
                        activeKey = 0;
                    }
                } else if (panes.length && activeKey > targetKey) {
                    activeKey = activeKey - 1;
                }
                this.panes = panes;
                this.activeKey = activeKey;
            },
            //当编辑器内容改变时触发
            changeValue(val) {
            },
            //判断文件名是否重复
            handleFileName(rule, value, callback) {
                let isRepeat
                if (this.isAdd) {
                    isRepeat = this.panes.some(item => {
                        return value == item.tabName
                    })
                } else {
                    isRepeat = this.panes.some((item, index) => {
                        return value == item.tabName && index != this.activeKey
                    })
                }

                if (isRepeat) {
                    callback('文件名重复！')
                }
                // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
                callback()
            },
        },
        created() {
            this.form = this.$form.createForm(this, {
                onValuesChange: (props, values) => {
                    // console.log(values)
                    //监听模板种类变化 与一级tab主附表联动
                }
            })
            // 防止表单未注册
            fields.forEach((v) => this.form.getFieldDecorator(v));
            // 当 model 发生改变时，为表单设置值
            this.$watch("model", () => {
                if (this.model) {
                    if (Object.keys(this.model).length != 0) {
                        this.panes = JSON.parse(JSON.stringify(this.model.templateJson));
                    } else {
                        this.panes = [{tabData: '', tabName: 'newTab'}];
                    }
                }
                this.model && this.form.setFieldsValue(pick(this.model, fields));
            });
        },
    };
</script>
